package xin.shaozeming.base.common.utils;

import java.security.MessageDigest;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by jackhuang on 2016/3/15.
 */
public class RandomCode {

    /**
     * 生成6位随机码
     *
     * @return
     */
    public static String generateCaptcha() {
        int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Random rand = new Random();
        for (int i = 10; i > 1; i--) {
            int index = rand.nextInt(i);
            int tmp = array[index];
            array[index] = array[i - 1];
            array[i - 1] = tmp;
        }
        int result = 0;
        for (int i = 0; i < 6; i++)
            result = result * 10 + array[i];
        return String.valueOf(result).length() < 6 ? generateCaptcha() : String.valueOf(result);
    }

    /**
     * 生成随机码
     *
     * @param strLength 随机码长度
     * @return
     */
    public static String generateRandomCode(int strLength) {
        Random rm = new Random();
        // 获得随机数
        Double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
        // 将获得的获得随机数转化为字符串
        String result = String.format("%.0f", pross);
        // 返回固定的长度的随机数
        return result.substring(0, strLength);
    }

    /**
     * token算法： UUID  MD5
     *
     * @return
     */
    public static String createToken() {
        return MD5(UUID.randomUUID().toString());
    }

    public static String MD5(String s) {
        if (s == null && "".equals(s)) {
            return null;
        }

        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    private static AtomicInteger aint = new AtomicInteger(0);

    /**
     * @param @return 设定文件
     * @return long    返回类型
     * @throws
     * @Title: getNumberID
     * @Description: ID生成
     */
    synchronized public static long getNumberID() {
        return System.currentTimeMillis() * 100 + aint.incrementAndGet();
    }

//    public static void main(String[] args) {
//        for (int i = 0; i < 1000; i++) {
//            System.out.println(generateRandomCode(4));
//        }
//    }
}
